package fh.app4stud.mensa;

import android.app.Service;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import fh.app4stud.mensa.database.MenuDbAdapter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;

/**
 * This class gets the xml with all the menus and parsers it to retrieve the
 * menses by days. This service is called only once a week on sunday. The menus
 * from previous week is dropped and new table is created with new menus.
 * 
 * Created by IntelliJ IDEA. User: ifi Date: 22.04.11 Time: 00:35 To change this
 * template use File | Settings | File Templates.
 */
public class MensaMenuService extends Service {

	// variables
	private final IBinder menuServiceBinder;
	private MenuDbAdapter menuDbHelper;

	private final String TAG = "MENU SERVICE TAG";

	public MensaMenuService() {
		menuServiceBinder = new MensaBinder();
	}

	@Override
	public void onCreate() {
		Log.i(TAG,
				"Creating Menu Service**********************************************");

		menuDbHelper = new MenuDbAdapter(this);

	}

	@Override
	public IBinder onBind(Intent intent) {
		return menuServiceBinder;
	}

	public class MensaBinder extends Binder {
		public MensaMenuService getMensaMenuService() {
			Log.i(TAG, "Returning the service");
			return MensaMenuService.this;
		}
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		try {
			Log.i(TAG, "Reading the document");
			Resources myResources = getResources();
			InputStream inputStream = myResources.openRawResource(R.raw.menues);
			DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder documentBuilder = documentBuilderFactory
					.newDocumentBuilder();
			Document document = documentBuilder.parse(inputStream);
			Element documentElement = document.getDocumentElement();
			addMenus(documentElement);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}

		return Service.START_NOT_STICKY;
	}

	private void addMenus(Element documentElement) {
		Log.i(TAG, "In addMenus");
		menuDbHelper.open();
		menuDbHelper.deleteRecords("menu"); // delete the table and create a
											// fresh one for this week

		NodeList locationNodeList = documentElement
				.getElementsByTagName("location");

		if (locationNodeList != null && locationNodeList.getLength() > 0) {

			for (int i = 0; i < locationNodeList.getLength(); i++) { // locations
				Log.i(TAG, "going trough locations");

				Element location = (Element) locationNodeList.item(i);

				String locStr = location.getAttribute("name");
				int locId = Integer.parseInt(location.getAttribute("id"));

				NodeList daysNodeList = location.getElementsByTagName("day");

				Log.i(TAG, "going trough days");
				if (daysNodeList != null && daysNodeList.getLength() > 0) {

					for (int ii = 0; ii < daysNodeList.getLength(); ii++) {
						Element day = (Element) daysNodeList.item(ii);

						NodeList menuNodeList = day
								.getElementsByTagName("menu");

						String dayStr = day.getAttribute("name");
						int dayId = Integer.parseInt(day.getAttribute("id"));
						// it's opened before in the code, but there is an error
						// sometimes at this point and it says
						// that the menuDbHelper is not open...
						// menuDbHelper.open();

						if (menuNodeList != null
								&& menuNodeList.getLength() > 0) {

							for (int iii = 0; iii < menuNodeList.getLength(); iii++) {
								Element menuNode = (Element) menuNodeList
										.item(iii);
								int menuId = Integer.parseInt(menuNode
										.getElementsByTagName("id").item(0)
										.getFirstChild().getNodeValue());
								String name = menuNode
										.getElementsByTagName("name").item(0)
										.getFirstChild().getNodeValue();
								String price = menuNode
										.getElementsByTagName("price").item(0)
										.getFirstChild().getNodeValue();
								String item1 = menuNode
										.getElementsByTagName("item1").item(0)
										.getFirstChild().getNodeValue();
								String item2 = menuNode
										.getElementsByTagName("item2").item(0)
										.getFirstChild().getNodeValue();

								Log.i(TAG, "adding : " + locStr + ",  "
										+ dayStr + ",  " + menuId + ",  "
										+ name + ",  " + price + ",  " + item1
										+ ",  " + item2 + ",  " + "in"
										+ menuDbHelper.toString());
								menuDbHelper.createItem(locId, locStr, dayId,
										dayStr, menuId, name, price, item1);
								menuDbHelper.createItem(locId, locStr, dayId,
										dayStr, menuId, name, price, item2);

							}
							;
						}
					}
				}
			}
		}
		menuDbHelper.close();
	}
}
